/*
package com.own.demo.lwf.utils.workUtils;
package com.own.demo.workUtils;

import cn.hsa.cep.plc.std.common.adapt.dict.entity.DataDictDO;
import cn.hsa.hsaf.core.fsstore.FSAccessControlList;
import cn.hsa.hsaf.core.fsstore.FSEntity;
import cn.hsa.hsaf.core.fsstore.FSManager;
import cn.hsa.mbs.common.exception.MbsException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

*
 * Created with IntelliJ IDEA.
 * User: caiww
 * Date: 2019-09-06
 * Time: 16:33
 * Description: 文件上传下载工具类


@Service
@Slf4j
public class FileUploadDownloadUtil {

    @Resource
    private FSManager fsManager;

*
     * 上传文件
     *
     * @param file     需要上传的文件
     * @param bucket   bucket
     * @param fileName 需要保存的文件名
     * @return 保存完成的文件名


    public String uploadFile(MultipartFile file, String bucket, String fileName) throws Exception {
        FSEntity fsEntity = new FSEntity();
        try {
            fsEntity.setInputstream(file.getInputStream());
            fsEntity.setName(bucket + "/" + fileName);
            fsEntity.setSize(file.getSize());
            fsManager.putObject(bucket, fsEntity);
        } catch (Exception e) {
            throw new MbsException("上传文件出错：" + fileName + e.getMessage());
        }
        return fsEntity.getName();
    }
    public String uploadFileLocal(MultipartFile file, String bucket, String fileName,String fileUrl) throws Exception {
        FSEntity fsEntity = new FSEntity();
        try {
            fsEntity.setInputstream(file.getInputStream());
            fsEntity.setName(fileUrl + fileName);
            fsEntity.setSize(file.getSize());
            fsEntity.setAcl(FSAccessControlList.PublicReadWrite);
            fsManager.putObject(bucket, fsEntity);
        } catch (Exception e) {
            throw new MbsException("上传文件出错：" + fileName + e.getMessage());
        }
        return fsEntity.getName();
    }
*
     * 文件下载
     *
     * @param response    响应
     * @param fileName    需要下载的文件名
     * @param newFileName 下载成新的文件名


    public void downloadFile(HttpServletResponse response, String bucket, String fileName, String newFileName) throws Exception {
        FSEntity fsEntity = fsManager.getObject(bucket, "mbstest/" + fileName);
        if (!ValidateUtil.isEmpty(fsEntity)) {
            InputStream inputStream = fsEntity.getInputstream();
            downloadFile(response, fsEntity.getContentType(), fsEntity.getInputstream(), newFileName);
            IOUtils.closeQuietly(inputStream);
        } else {
            throw new MbsException("找不到需要下载的文件");
        }
    }

*
     * 文件下载
     *
     * @param response    响应
     * @param contentType 响应内容类型
     * @param inputStream 输入流
     * @param fileName    文件名


    public void downloadFile(HttpServletResponse response, String contentType, InputStream inputStream, String fileName)  throws Exception{
        OutputStream myout = BusinessConst.OUTPUT_STREAM_NULL;
        try {
            String newFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType(contentType);
            response.addHeader("Content-Disposition", "attachment; filename=\"" + newFileName + "\"");
            BufferedInputStream input = new BufferedInputStream(inputStream);
            myout = response.getOutputStream();
            //开始循环下载
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = input.read(buff, 0, buff.length))) {
                myout.write(buff, 0, bytesRead);
            }
            myout.flush();
        } catch (Exception e) {
            throw new MbsException("下载出错：" + e.getMessage());
        } finally {
            if(myout!=null) {
                IOUtils.closeQuietly(myout);
            }
        }
    }

*
     * 删除文件
     *
     * @param fileName 需要删除的文件名
     * @return


    public boolean deleteFile(String bucket, String fileName) {
        return fsManager.deleteObject(bucket, "mbstest/" + fileName);
    }

*
     * 获取文件链接地址
     *
     * @param fileName
     * @return


    public String getFileUrl(String endpoint, String bucket, String fileName) {
        return "http://" + bucket + "." + endpoint + "/" + fileName;
    }

    public String getFileUrlwx(String endpoint, String bucket, String fileName) {
        return endpoint + "/" + fileName;
    }

*
     * 获取文件流
     *
     * @param fileName 文件名
     * @return 文件输入流
     * @author caiww
     * @date 2019/10/11


    public InputStream getFileStream(String bucket, String fileName)  throws Exception{
        FSEntity file = fsManager.getObject(bucket, "mbstest/" + fileName);
        if (ValidateUtil.isEmpty(file)) {
            throw new MbsException("无法文件名：" + fileName + "的文件");
        }
        return file.getInputstream();
    }

    public InputStream getFileWXStream(String bucket, String fileName)  throws Exception{
        FSEntity file = fsManager.getObject(bucket, fileName);
        if (ValidateUtil.isEmpty(file)) {
            throw new MbsException("无法文件名：" + fileName + "的文件");
        }
        return file.getInputstream();
    }

*
     * 对象转map
     *
     * @param obj 对象
     * @throws java.lang.Exception


    public Map<String, String> objToMap(Object obj) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        // 获取f对象对应类中的所有属性域
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            //将key置为小写，默认为对象的属性
            varName = varName.toLowerCase();
            try {
                // 获取原来的访问控制权限
               // boolean accessFlag = fields[i].isAccessible();
                // 修改访问控制权限
                //fields[i].setAccessible(true);
                ReflectionUtils.makeAccessible(fields[i]);
                // 获取在对象f中属性fields[i]对应的对象中的变量
                Object o = fields[i].get(obj);
                if (o != null) {
                    map.put(varName, o.toString());
                }
                                // 恢复访问控制权限
               // fields[i].setAccessible(accessFlag);
            } catch (IllegalArgumentException | IllegalAccessException ex){
                throw new MbsException(ex.getMessage());
            }
        }
        return map;
    }

*
     * 公用xls 文件转换成 list （不允许中间空行）
     *
     * @param is           文件输入流
     * @param fieldNames   属性名
     * @param dtoClassPath 对应DTO类全路径
     * @param row          需要跳过的行数(包括标题行)
     * @return excel中获取的list
     * @author caiww
     * @date 2019/10/11


    public List excelToList(InputStream is, String fieldNames, String dtoClassPath, int row) throws Exception {
        List retList = new ArrayList();
        String[] fieldName = fieldNames.split(",");
        int errorRow = 1;
        try {
            WorkbookSettings workbookSettings = new WorkbookSettings();
            Workbook book = Workbook.getWorkbook(is, workbookSettings);

            Sheet sheet = book.getSheet(0);

            String cresult = "";
            Object tmpObj = null;
            for (int nn = row; nn < sheet.getRows(); nn++) {
                errorRow = nn + 1;
                String[] values = new String[fieldName.length];
                for (int mm = 0; mm < fieldName.length; mm++) {
                    Cell cell1 = sheet.getCell(mm, nn);
                    cresult = cell1.getContents();
                    values[mm] = cresult.trim();
                }
                try {
                    tmpObj = generatorObjectFromArray(fieldName, values, dtoClassPath);
                    int valuesLength = values.length;
                    boolean flag = false;
                    for (int a = 0; a < valuesLength; a++) {
                        if (!ValidateUtil.isEmpty(values[a])) {
                            flag = true;
                            break;
                        }
                    }
                    if (flag) {
                        retList.add(tmpObj);
                    } else {
                        break;
                    }

                } catch (Exception e) {
                    throw new MbsException("在第" + (nn + 1) + "行数据格式不符合要求，请检查！" + e.getMessage());
                }
            }
        } catch (Exception e) {
            throw new MbsException("数据导入出错！" + e.getMessage() + "出错行：" + errorRow);
        }
        return retList;
    }

*
     * 导出数据
     *
     * @param headName   列名
     * @param headId     列ID
     * @param collection 码值
     * @param list       数据
     * @param fileName   文件名
     * @param response   响应
     * @throws java.lang.Exception


    public void exportExcel(List<String> headName, List<String> headId, List<DataDictDO> collection, List list,
                            String fileName, HttpServletResponse response) throws Exception {
        //HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFWorkbook workbook = null;
        ServletOutputStream outputStream = null;
        try{
            workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("sheet1");
            HSSFRow rowHead = sheet.createRow(0);
            for (int j = 0; j < headName.size(); j++) {
                HSSFCell cell = rowHead.createCell(j);
                HSSFRichTextString text = null;
                if ("".equals(headName.get(j)) || headName.get(j) == null) {
                    text = new HSSFRichTextString("");
                } else {
                    text = new HSSFRichTextString(headName.get(j));
                }
                cell.setCellValue(text);
            }
            Object obj = null;
            Map map = new HashMap();
            for (int i = 1; i <= list.size(); i++) {
                HSSFRow row = sheet.createRow(i);
                obj = list.get(i - 1);
                map = objToMap(obj);
                for (int j = 0; j < headName.size(); j++) {
                    HSSFCell cell = row.createCell(j);
                    HSSFRichTextString text = new HSSFRichTextString();
                    if ("".equals(map.get(headId.get(j))) || map.get(headId.get(j)) == null) {
                        text = new HSSFRichTextString("");
                    } else {
                        if (!ValidateUtil.isEmpty(collection)) {
                            for (DataDictDO dataDictDO : collection) {
                                if (dataDictDO.getName().equals(headName.get(j))) {
                                    if (map.get(headId.get(j)).equals(dataDictDO.getValue())) {
                                        text = new HSSFRichTextString(dataDictDO.getLabel());
                                        break;
                                    }
                                } else {
                                    text = new HSSFRichTextString(map.get(headId.get(j)).toString());
                                }
                            }
                        } else {
                            text = new HSSFRichTextString(map.get(headId.get(j)).toString());
                        }
                    }
                    if(!ValidateUtil.isEmpty(text)) {
                        cell.setCellValue(text);
                    }
                }
            }
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
        }
        catch (Exception e){
            throw new MbsException(e.getMessage());
        }
        finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    log.error("workbook关闭错误");
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("outputStream关闭错误");
                }
            }
        }
    }

*
     * 根据属性名将excel行数据转换为对象
     *
     * @param fieldNames
     * @param values
     * @param dtoClassPath
     * @return
     * @throws java.lang.Exception


    private Object generatorObjectFromArray(String[] fieldNames, String[] values, String dtoClassPath) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        if (fieldNames.length != values.length) {
            throw new MbsException("属性数量与实际数据数量不符");
        }
        if (values.length == 0) {
            throw new MbsException("行数据为空，无法转换");
        }
        Class<?> aClass = Class.forName(dtoClassPath);
        Field[] declaredFields = aClass.getDeclaredFields();
        Object o = aClass.newInstance();
        for (Field field : declaredFields) {
            for (int i = 0; i < fieldNames.length; i++) {
                String filedName = fieldNames[i];
                if (ValidateUtil.areEqual(filedName, field.getName())) {
                    //field.setAccessible(true);
                    ReflectionUtils.makeAccessible(field);
                    if (ValidateUtil.areEqual(field.getGenericType().toString(), "class java.util.Date")) {
                        field.set(o, sdf.parse(values[i]));
                    } else if (ValidateUtil.areEqual(field.getGenericType().toString(), "class java.sql.Timestamp")) {
                        field.set(o, Timestamp.valueOf(values[i]));
                    } else if (ValidateUtil.areEqual(field.getGenericType().toString(), "class java.math.BigDecimal")) {
                        field.set(o, new BigDecimal(values[i]));
                    } else if (ValidateUtil.areEqual(field.getGenericType().toString(), "class java.lang.String")) {
                        field.set(o, values[i]);
                    } else if (ValidateUtil.areEqual(field.getGenericType().toString(), "class java.lang.Integer")) {
                        field.set(o, Integer.valueOf(values[i]));
                    } else if (ValidateUtil.areEqual(field.getGenericType().toString(), "class java.lang.Double")) {
                        field.set(o, new Double(values[i]));
                    }
                }
            }
        }
        return o;
    }
}
*/
